package org.gitee.weapp.controller;

import org.apache.commons.lang3.StringUtils;
import org.gitee.weapp.domain.AjaxResult;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.domain.vo.LoginUser;
import org.gitee.weapp.service.LoginService;
import org.gitee.weapp.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/sys")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HttpServletRequest request;

    @Value("${server.remote-address}")
    private String host;

    @Value("${server.port}")
    private Integer port;

    @PostMapping("/token")
    public AjaxResult getToken(@RequestBody LoginUser loginUser) {
        try {
            String toke = loginService.createToken(loginUser);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("token", toke);
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/getUser")
    public AjaxResult getUser() {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error("用户未登录");
        }
        if (!StringUtils.startsWith(sysUser.getAvatarUrl(), "http")) {
            sysUser.setAvatarUrl("http://" + host + ':' + port + sysUser.getAvatarUrl());
        }
        return AjaxResult.success(sysUser);
    }

    @PostMapping("/phone")
    public AjaxResult postPhoneNumber(@RequestParam("code") String code) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.unAuthorizeError();
        }

        loginService.getPhoneNumber(code, sysUser);
        return AjaxResult.success();
    }
}
